package com.my.study.juc;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author: yidujun
 * @create: 2021/03/20 12:40
 */
@Slf4j
public class CompletableFutureTest {

    @Test
    public void test01() throws Exception {
        CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("xxx");
        }).get(1, TimeUnit.SECONDS);
    }

    @Test
    public void test02() {
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future1");
        });

        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future2");
        });

        allOfComplete(future1, future2);

    }

    private void allOfComplete(CompletableFuture<Void>... futures) {
        try {
            CompletableFuture.allOf(futures).whenComplete((r, t) -> {
                System.out.println(r);
                System.out.println(t);
                // do something
            }).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }


}
